package model

import (
	"errors"
	"fmt"
	"ordersystem/config"
	"ordersystem/database"
	"time"
)

type User struct {
	Id       int32     `json:"id" xml:"id" form:"id" gorm:"primaryKey"`
	Name     string    `json:"name" xml:"name" form:"name"`
	Identify int8      `json:"identify" xml:"identify" form:"identify"`
	Creator  int32     `json:"creator" xml:"creator" form:"creator"`
	Belong   string    `json:"belong" xml:"belong" form:"belong"`
	Telphone string    `json:"telphone" xml:"telphone" form:"telphone"`
	Password string    `json:"password" xml:"password" form:"password"`
	CreateAt time.Time `json:"create_at" xml:"create_at" form:"create_at" gorm:"autoCreateTime"`
	UpdateAt time.Time `json:"update_at" xml:"update_at" form:"update_at" gorm:"autoUpdateTime"`
}

func (u *User) QueryUserByPassword() {
	conn := database.GetMysqlConnection()
	conn.Table(config.TABLE_USERS).Where("telphone = ? and password = ?", u.Telphone, u.Password).First(u)
}

func (u *User) QueryUser() error {
	conn := database.GetMysqlConnection()
	conn.Model(u).First(u)
	return nil
}

func QueryUserNumber(id int32) (int64, error) {
	conn := database.GetMysqlConnection()
	var result int64
	if id == 0 {
		conn.Table(config.TABLE_USERS).Count(&result)
	} else {
		conn.Table(config.TABLE_USERS).Where("creator = ?", id).Count(&result)
	}
	return result, nil
}

func QueryUsersForAdminOrSuperAdmin(page int, id int32) (interface{}, error) {
	conn := database.GetMysqlConnection()

	var result []map[string]interface{}

	if id == 0 {
		conn.Model(&User{}).Offset(config.PAGE_SIZE * page).Limit(config.PAGE_SIZE).Scan(&result)
	} else {
		conn.Model(&User{}).Where("creator = ?", id).Offset(config.PAGE_SIZE * page).Limit(config.PAGE_SIZE).Scan(&result)
	}
	fmt.Println(result)
	return result, nil
}

// func QueryUsersForAdmin(page int, uid uint) (interface{}, error) {
// 	conn := database.GetMysqlConnection()
// 	var result []User
// 	conn.Model(&User{}).Offset(config.PAGE_SIZE * page).Limit(config.PAGE_SIZE).Scan(result)
// 	return result, nil
// }

func (u *User) CreateUser() error {
	conn := database.GetMysqlConnection()

	affectedRows := conn.Model(u).Create(u).Commit().RowsAffected
	if affectedRows == 0 {
		return errors.New(config.RESPONSE_DATABASE_OPERATION_ERROR)
	}
	return nil
}

func (u *User) UpdateUser() error {
	fmt.Println(u)
	if u.Identify == 0 {
		return errors.New(config.RESPONSE_DATABASE_OPERATION_ERROR)
	}

	conn := database.GetMysqlConnection()

	if conn.Model(u).Save(u).Commit().RowsAffected == 0 {
		return errors.New(config.RESPONSE_DATABASE_OPERATION_ERROR)
	}
	return nil
}

func (u *User) DeleteUser() error {
	conn := database.GetMysqlConnection()

	if conn.Model(u).Delete(u).Commit().RowsAffected == 0 {
		return errors.New(config.RESPONSE_DATABASE_OPERATION_ERROR)
	}
	return nil
}
